package top.vains.util;

import org.jcodec.api.FrameGrab;
import org.jcodec.common.model.Picture;
import org.jcodec.scale.AWTUtil;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import top.vains.entity.Files;
import top.vains.exception.CustomerException;
import top.vains.service.IFilesService;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;

/**
 * 视频帮助类
 *
 * @author vains
 * @version 1.0
 * @since 2020/3/15 13:05
 **/
public class VideoUtils {

    private VideoUtils(){}

    /**
     * 获取并且生成视频封面图
     * @param video 视频文件对象
     * @return 返回封面图保存地址(去除SpringBoot映射的文件前缀)
     */
    public static String createVideoCover(File video) {
        String filePath = video.getAbsolutePath() + ".jpg";
        try {
            Picture picture = FrameGrab.getFrameFromFile(video, 1);
            BufferedImage bufferedImage = AWTUtil.toBufferedImage(picture);
            ImageIO.write(bufferedImage, "jpg", new File(filePath));
        } catch (Exception e) {
            throw new CustomerException("视频封面图获取失败");
        }
        return filePath.substring(11);
    }

    /**
     * 获取所有父节点的路径
     * @param fileId 文件ID(父节点)
     * @param filesService 文件服务对象
     * @param path 调用时请传入 null 或 ""(递归时会用到)
     * @return 返回所有父节点的路径组成的路径
     */
    public static String getParentPath(Integer fileId, IFilesService filesService, String path) {
        if (fileId == 0) {
            return path;
        }
        Files files = filesService.getById(fileId);
        Assert.notNull(files, "文件不存在！");
        if (files.getFileParentId() == null) {
            return files.getFileName();
        }
        if (StringUtils.isEmpty(path)) {
            path = files.getFileName();
        } else {
            path = files.getFileName() + "/" + path;
        }
        return getParentPath(files.getFileParentId(), filesService, path);
    }

}
